import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtCharts 2.3

/**
 * 实时曲线图组件
 */
ChartView {
    id: chartView

    // 允许在 Layout 中自动拉伸
    Layout.fillWidth: true
    Layout.fillHeight: true
    Layout.preferredHeight: 180

    // 公开属性
    property string chartType: "temperature"
    property int maxDataPoints: 60
    property bool autoScroll: true
    property color lineColor: "#3b82f6"
    property real lineWidth: 2.5
    property bool showPoints: false

    // 留出空间给坐标轴刻度与标题，避免左侧被裁切
    property int marginLeft: 40
    property int marginRight: 10
    property int marginTop: 8
    property int marginBottom: 28
    property int axisLabelFontSize: 11
    property int axisTitleFontSize: 11
    property int axisLabelPadding: 14
    property int axisTitleSpacing: 4

    readonly property int safeLeftMargin: Math.max(marginLeft, calculateAxisMargin())

    // 图表配置（尽量占满空间）
    antialiasing: true
    backgroundColor: "transparent"
    legend.visible: false
    title: ""
    margins.top: marginTop
    margins.bottom: marginBottom
    margins.left: safeLeftMargin
    margins.right: marginRight

    // X 轴
    ValueAxis {
        id: axisX
        min: 0
        max: maxDataPoints
        tickCount: 7
        labelFormat: "%d"
        gridVisible: true
        lineVisible: false
        labelsColor: "#6b7280"
        labelsFont.pixelSize: axisLabelFontSize
        titleText: ""
    }

    // Y 轴
    ValueAxis {
        id: axisY
        min: getMinValue()
        max: getMaxValue()
        tickCount: 6
        labelFormat: "%.1f"
        gridVisible: true
        lineVisible: false
        labelsColor: "#6b7280"
        labelsFont.pixelSize: axisLabelFontSize
        titleText: getYAxisTitle()
        titleFont.pixelSize: axisTitleFontSize
    }

    // 折线
    LineSeries {
        id: dataSeries
        axisX: axisX
        axisY: axisY
        color: chartView.lineColor
        width: chartView.lineWidth
        pointsVisible: chartView.showPoints
        pointLabelsVisible: false
    }

    property int currentDataIndex: 0

    function addDataPoint(value) {
        dataSeries.append(currentDataIndex, value)
        if (dataSeries.count > maxDataPoints) {
            dataSeries.remove(0)
        }
        currentDataIndex++
        if (autoScroll && currentDataIndex > maxDataPoints) {
            axisX.min = currentDataIndex - maxDataPoints
            axisX.max = currentDataIndex
        }
        autoAdjustYAxis()
    }

    function addDataPoints(values) {
        for (var i = 0; i < values.length; i++) addDataPoint(values[i])
    }

    function clearData() {
        dataSeries.removePoints(0, dataSeries.count)
        currentDataIndex = 0
        axisX.min = 0
        axisX.max = maxDataPoints
    }

    function updateDataSeries(values) {
        dataSeries.removePoints(0, dataSeries.count)
        for (var i = 0; i < values.length; i++) dataSeries.append(i, values[i])
        currentDataIndex = values.length
        if (values.length > maxDataPoints) {
            axisX.min = values.length - maxDataPoints
            axisX.max = values.length
        } else {
            axisX.min = 0
            axisX.max = maxDataPoints
        }
        autoAdjustYAxis()
    }

    function setTemperatureChart() {
        chartType = "temperature"
        lineColor = "#ef4444"
        axisY.min = getMinValue(); axisY.max = getMaxValue(); axisY.titleText = getYAxisTitle()
    }
    function setPressureChart() {
        chartType = "pressure"
        lineColor = "#3b82f6"
        axisY.min = getMinValue(); axisY.max = getMaxValue(); axisY.titleText = getYAxisTitle()
    }
    function setFlowChart() {
        chartType = "flow"
        lineColor = "#10b981"
        axisY.min = getMinValue(); axisY.max = getMaxValue(); axisY.titleText = getYAxisTitle()
    }

    function getMinValue() {
        switch(chartType) {
        case "temperature": return 40
        case "pressure": return 200
        case "flow": return 20
        default: return 0
        }
    }
    function getMaxValue() {
        switch(chartType) {
        case "temperature": return 120
        case "pressure": return 800
        case "flow": return 150
        default: return 100
        }
    }
    function getYAxisTitle() {
        switch(chartType) {
        case "temperature": return "温度 (℃)"
        case "pressure": return "压力 (kPa)"
        case "flow": return "流量 (L/min)"
        default: return ""
        }
    }

    function autoAdjustYAxis() {
        if (dataSeries.count === 0) return
        var min = Number.MAX_VALUE, max = -Number.MAX_VALUE
        for (var i = 0; i < dataSeries.count; i++) {
            var p = dataSeries.at(i)
            if (p.y < min) min = p.y
            if (p.y > max) max = p.y
        }
        if (min === Number.MAX_VALUE || max === -Number.MAX_VALUE) return
        var span = Math.max(1, max - min)
        var margin = span * 0.2
        axisY.min = Math.max(0, min - margin)
        axisY.max = max + margin
    }

    FontMetrics {
        id: axisLabelMetrics
        font.pixelSize: axisLabelFontSize
    }

    FontMetrics {
        id: axisTitleMetrics
        font.pixelSize: axisTitleFontSize
    }

    function calculateAxisMargin() {
        var longest = getLongestAxisLabel()
        var labelWidth = axisLabelMetrics.advanceWidth(longest.length > 0 ? longest : "0")
        var titleSpace = (axisY.titleText && axisY.titleText.length > 0) ? axisTitleMetrics.height + axisTitleSpacing : 0
        return Math.round(labelWidth + axisLabelPadding + titleSpace)
    }

    function getLongestAxisLabel() {
        var candidates = [axisY.min, axisY.max]
        var span = axisY.max - axisY.min
        if (span > 0 && axisY.tickCount > 2) {
            var step = span / (axisY.tickCount - 1)
            candidates.push(axisY.min + step)
            candidates.push(axisY.max - step)
        }
        var longest = ""
        for (var i = 0; i < candidates.length; i++) {
            var label = formatAxisLabel(candidates[i])
            if (label.length > longest.length)
                longest = label
        }
        return longest.length > 0 ? longest : "0"
    }

    function formatAxisLabel(value) {
        var format = axisY.labelFormat || "%.1f"
        if (format.indexOf("%d") !== -1)
            return format.replace("%d", Math.round(value))
        var match = format.match(/%\.?(\d*)f/)
        if (match) {
            var precision = match[1] === "" ? 0 : parseInt(match[1], 10)
            return format.replace(match[0], Number(value).toFixed(precision))
        }
        return value.toFixed(1)
    }

    Component.onCompleted: {
        console.log("✅ RealtimeChart 初始化完成")
        console.log("  - 图表类型:", chartType)
        console.log("  - 最大数据点:", maxDataPoints)
    }
}

